const {
  getList,
  getDetail,
  addBlog,
  updateBlog,
  delBlog
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')

// 统一的登录验证
const loginCheck = req => {
  if (!req.session.username) {
    return Promise.resolve(new ErrorModel('尚未登录'))
  }
}

const handleBlogRouter = (req, res) => {
  const method = req.method // 获取方法
  const id = req.query.id

  // 获取博客列表
  if (method === 'GET' && req.path === '/api/blog/list') {
    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    const result = getList(author, keyword)

    return result.then(data => {
      return new SuccessModel(data)
    })
  }

  // 获取博客详情
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const result = getDetail(id)

    return result.then(data => {
      return new SuccessModel(data)
    })
  }

  // 新增一篇博客
  if (method === 'POST' && req.path === '/api/blog/add') {
    const loginCheckResult = loginCheck(req)
    // 未登录
    if (loginCheckResult) {
      return loginCheckResult
    }

    req.body.author = req.session.username
    const result = addBlog(req.body)
    return result.then(data => {
      // return new SuccessModel(data)
      return new SuccessModel(data, '添加成功')
    })
  }

  // 更新一篇博客
  if (method === 'POST' && req.path === '/api/blog/update') {
    const loginCheckResult = loginCheck(req)
    // 未登录
    if (loginCheckResult) {
      return loginCheckResult
    }

    const result = updateBlog(id, req.body)
    return result.then(data => {
      if (data) {
        return new SuccessModel('更新博客成功')
      } else {
        return new ErrorModel('更新博客失败!')
      }
    })
  }

  // 删除一篇博客
  if (method === 'POST' && req.path === '/api/blog/del') {
    const loginCheckResult = loginCheck(req)
    // 未登录
    if (loginCheckResult) {
      return loginCheckResult
    }

    const author = req.session.username
    const result = delBlog(id, author)
    return result.then(data => {
      if (data) {
        return new SuccessModel('删除博客成功')
      } else {
        return new ErrorModel('删除博客失败!')
      }
    })
  }
}

module.exports = handleBlogRouter
